const fs = require('fs');
const path = require('path');
const Busboy = require('busboy');

// 写入目录
const mkdirsSync = dirname => {
  if(fs.existsSync(dirname)) {
    return true
  } else {
    if(mkdirsSync(path.dirname(dirname))) {
      fs.mkdirSync(dirname)
      return true;
    }
  }
  return false;
}

const getSuffix = (filename) => {
  return filename.split('.').pop();
}

// 重命名文件
const rename = filename => {
  return Math.random().toString(16).substr(2) + '.' + getSuffix(filename);
}

// 删除文件
const removeTemImage = path => {
  fs.unlink(path, err => {
    if(err){
      throw err
    }
  })
}

// 文件上传处理
const uploadFile = (ctx, options) => {
  const _emmiter = new Busboy({headers: ctx.req.headers})
  const fileType = options.fileType
  const filePath = path.join(options.path, fileType)
  const confirm = mkdirsSync(filePath);
  if(!confirm) {
    return
  }
  console.log("开始上传");
  return new Promise((resolve,reject) => {
    _emmiter.on('file',(fieldname,file,filename,encoding,mimetype) => {
      const fileName = rename(filename);
      const saveTo = path.join(path.join(filePath,fileName))
      file.pipe(fs.createWriteStream(saveTo));
      file.on('end',() => {
        resolve({
          imgPath: `/${fileType}/${fileName}`,
          imgKey: fileName
        })
      })
    })
    _emmiter.on('finish',() => {console.log('上传结束')});
    _emmiter.on('error',() => {console.log('err'); reject(err)});
    ctx.req.pipe(_emmiter)
  })
} 

module.exports = {
  uploadFile: uploadFile,
  removeTemImage: removeTemImage,
}
